package com.xqboss.apps.service.user;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xqboss.apps.domain.user.UserIdentityPermBasic;
import com.xqboss.apps.domain.user.UserIdentityPermWrenchProduction;
import com.xqboss.apps.domain.user.UserIdentityRank;
import com.xqboss.apps.dto.user.DeleteWrenchProductionDto;
import com.xqboss.apps.dto.user.OpenOrCloseWrenchFactoryDto;
import com.xqboss.apps.mapper.user.UserIdentityPermWrenchProductionMapper;
import com.xqboss.chain.domain.chain.dto.BaseRequest;
import com.xqboss.common.exception.ServiceException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 木鱼
 * @since 2024-01-09
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class UserIdentityPermWrenchProductionService extends ServiceImpl<UserIdentityPermWrenchProductionMapper, UserIdentityPermWrenchProduction> {
    @Autowired
    private UserIdentityRankService userIdentityRankService;

    public List<UserIdentityPermWrenchProduction> selectBasicList(BaseRequest request) {
        return baseMapper.selectList(Wrappers.<UserIdentityPermWrenchProduction>lambdaQuery());
    }

    public UserIdentityPermWrenchProduction selectByIdBasic(Long id) {
        return baseMapper.selectById(id);
    }

    public boolean saveBasic(UserIdentityPermWrenchProduction record) {
        return baseMapper.insert(record) > 0;
    }

    public boolean updateBasic(UserIdentityPermWrenchProduction record) {
        return baseMapper.updateById(record) > 0;
    }

    /**
     * 修改套餐前置检查
     *
     * @param
     * @return
     */
    public void checkFactoryStatus(Long identityRankId) {
        Assert.notNull(identityRankId,()->new ServiceException("身份段位id不能为空!"));
        UserIdentityRank one = userIdentityRankService.getById(identityRankId);
        Assert.notNull(one,()->new ServiceException("段位信息不存在!"));
        if (one.getIsOpenWrenchProduction()) {
            throw new ServiceException("请关闭生产开关之后再修改套餐");
        }

    }


    /**
     * 获取用户是否具备开启扳手工厂的权限
     *
     * @param userId
     * @return
     */
    public Boolean getIsOpen(Long userId) {
        try {
            return userIdentityRankService.getUserIdentityRank(userId).getIsOpenWrenchProduction();
        } catch (Exception e) { // 如果出现异常说明系统后台配置出现问题 直接返回false
            log.error("扳手生产配置出现异常  无配置 || 同一身份不止一份配置");
            return false;
        }
    }

    /**
     * 修改扳手工厂开关
     *
     * @param dto
     * @return
     */
    public void openOrCloseWrenchFactory(OpenOrCloseWrenchFactoryDto dto) {
        boolean update = this.userIdentityRankService.lambdaUpdate()
                .set(UserIdentityRank::getIsOpenWrenchProduction, dto.getOpenOrClose())
                .eq(UserIdentityRank::getId, dto.getIdentityRankId())
                .update();
        Assert.isTrue(update,()->new ServiceException("修改身份段位扳手开关失败!"));
    }

    /**
     * 新增扳手套餐
     *
     * @param record
     */
    public Boolean insert(UserIdentityPermWrenchProduction record) {
        LambdaQueryWrapper<UserIdentityPermWrenchProduction> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserIdentityPermWrenchProduction::getIdentityRankId, record.getIdentityRankId());
        List<UserIdentityPermWrenchProduction> list = baseMapper.selectList(lambdaQueryWrapper);
        if (list.size() >= 6) {
            throw new ServiceException("套餐数量限制6条,请删除不需要的再添加");
        }
        list.forEach(e -> {
            // 判断是否有相同的套餐
            if (e.getExpendHotBeans().compareTo(record.getExpendHotBeans()) == 0
                    && e.getDayProduction().compareTo(record.getDayProduction()) == 0
                    && e.getPredictOutputWrench().compareTo(record.getPredictOutputWrench()) == 0) {
                throw new ServiceException("已存在相同的套餐");
            }
        });
        return baseMapper.insert(record) > 0;
    }

    /**
     * 前台
     * 根据身份段位id查询所属的生产套餐
     *
     * @param identityRankId 身份段位id,
     * @return
     */
    public List<UserIdentityPermWrenchProduction> appListByIdentityRankId(Long identityRankId) {
        LambdaQueryWrapper<UserIdentityPermWrenchProduction> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserIdentityPermWrenchProduction::getIdentityRankId, identityRankId);
        return baseMapper.selectList(lambdaQueryWrapper);
    }

    /**
     * 后台
     * 根据身份id查询所属的生产套餐
     *
     * @param identityId 身份id,若该身份下有多个等级放回所有等级数据
     * @return
     */
    public List<List<UserIdentityPermWrenchProduction>> webListByIdentityRankIds(Long identityId) {
        List<UserIdentityRank> list = userIdentityRankService.lambdaQuery().eq(UserIdentityRank::getIdentityId, identityId).list();
        List<List<UserIdentityPermWrenchProduction>> productionss = CollUtil.newArrayList();
        if (CollUtil.isNotEmpty(list)) {
            List<UserIdentityPermWrenchProduction> productions;
            for (UserIdentityRank identityRank : list) {
                productions = this.lambdaQuery().eq(UserIdentityPermWrenchProduction::getIdentityRankId, identityRank.getId()).list();
                productionss.add(productions);
            }
        }
        return productionss;
    }

    /**
     * 删除套餐
     *
     * @param dto
     */
    public void delete(DeleteWrenchProductionDto dto) {
        Long id = dto.getId();
        Long identityRankId = dto.getIdentityRankId();
        // 扳手开关校验
        checkFactoryStatus(identityRankId);
        // 剩余套餐数量校验
        Long count = this.lambdaQuery().eq(UserIdentityPermWrenchProduction::getIdentityRankId, identityRankId).count();
        //
        if (count <= 1) {
            throw new ServiceException("套餐数量最低保留一条");
        }
        this.lambdaUpdate().set(UserIdentityPermWrenchProduction::getDelFlag,Boolean.TRUE).eq(UserIdentityPermWrenchProduction::getId,id).update();
    }
}